package Structure.MyLinkedList;

import java.util.Iterator;

/**
 * @author wang'ji'cheng
 * @date 2025/8/9
 */
public class DoublyLinkedListCycle implements Iterable<Integer>{


    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>(){
            //从哨兵的下一个开始遍历
            Node p = sentinel.next;
            @Override
            public boolean hasNext() {
                return p != sentinel;

            }

            @Override
            public Integer next() {
                int value = p.value;
                 p = p.next;
                 return value;
            }
        };
    }

    private static class Node {
        Node prev;
        int value;
        Node next;

        public Node(Node prev, int value, Node next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    private Node sentinel = new Node(null, -1, null);

    public DoublyLinkedListCycle() {
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
    }

    /**
     * 添加第一个节点
     * @param value
     */
     public void addFirst(int value) {
       Node prev =  sentinel;
       Node next =  sentinel.next;
       Node added = new Node(prev, value, next);
       prev.next = added;
       next.prev = added;

     }
}
